// ignore_for_file: unnecessary_null_comparison

import 'package:flutter/material.dart';
import 'package:flutter_widget/custom/custom_appbar.dart';

// ignore: must_be_immutable
class GetWidgetInfo extends StatefulWidget {
  String name;
  GetWidgetInfo({Key? key, required this.name}) : super(key: key);

  @override
  _GetWidgetInfoState createState() => _GetWidgetInfoState();
}

class _GetWidgetInfoState extends State<GetWidgetInfo> {
  final keyText = GlobalKey();
  late Size size = const Size(0, 0);
  late Offset position = const Offset(100, 100);

  void calculateSizeAndPosition() =>
      WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
        final RenderBox? box =
            keyText.currentContext!.findRenderObject() as RenderBox?;
        setState(() {
          position = box!.localToGlobal(Offset.zero);
          size = box.size;
        });
      });

  @override
  void initState() {
    super.initState();
  }

  @override
  // ignore: curly_braces_in_flow_control_structures, curly_braces_in_flow_control_structures, curly_braces_in_flow_control_structures
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppbar(widget.name, Theme.of(context).primaryColor),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          children: [
            buildText(),
            const SizedBox(
              height: 32,
            ),
            // ignore: deprecated_member_use
            ElevatedButton(
                onPressed: calculateSizeAndPosition,
                child: const Text(
                  '获取小部件信息',
                  style: TextStyle(
                    fontSize: 20,
                    color: Colors.white,
                  ),
                )),

            buildResult()
          ],
          mainAxisAlignment: MainAxisAlignment.center,
        ),
      ),
    );
  }

  Widget buildText() {
    return Text(
      '冷空气大幅度南下,请注意保暖',
      key: keyText,
    );
  }

  Widget buildResult() {
    // ignore: avoid_print
    print(size);
    // ignore: avoid_print
    print(position);
    if (size == null || position == null) return const Text('获取widget的位置信息和大小');
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      // ignore: prefer_const_literals_to_create_immutables
      children: [
        Text(
          '宽度:${size.width.toInt()}',
          style: const TextStyle(fontSize: 32),
        ),
        Text(
          '高度:${size.height.toInt()}',
          style: const TextStyle(fontSize: 32),
        ),
        Text(
          'x坐标:${position.dx.toInt()}',
          style: const TextStyle(fontSize: 32),
        ),
        Text(
          'y坐标:${position.dy.toInt()}',
          style: const TextStyle(fontSize: 32),
        ),
      ],
    );
  }
}
